package com.sky.aspect;

import com.sky.annotation.Autofill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {
    @SneakyThrows
    @Before("execution(* com.sky.mapper.*.*(*))&&@annotation(com.sky.annotation.Autofill)")
    public void autoFill(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Autofill autofill = signature.getMethod().getAnnotation(Autofill.class);
        Object pojo = joinPoint.getArgs()[0];
        if (autofill.value() == OperationType.INSERT) {
            Method m1 = pojo.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method m2 = pojo.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method m3 = pojo.getClass().getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method m4 = pojo.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            m1.invoke(pojo, LocalDateTime.now());
            m2.invoke(pojo, LocalDateTime.now());
            m3.invoke(pojo, BaseContext.getCurrentId());
            m4.invoke(pojo, BaseContext.getCurrentId());
        } else {
            // 修改操作: 修改俩个属性
            Method m1 = pojo.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method m2 = pojo.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            m1.invoke(pojo, LocalDateTime.now());
            m2.invoke(pojo, BaseContext.getCurrentId());
        }
    }
}
